package cn.drenal.capcap.controller.forum;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.drenal.capcap.common.Response;
import cn.drenal.capcap.entity.Comment;
import cn.drenal.capcap.entity.CommentLike;
import cn.drenal.capcap.entity.User;
import cn.drenal.capcap.entity.vo.forum.CommentVO;
import cn.drenal.capcap.mapper.CommentLikeMapper;
import cn.drenal.capcap.service.CommentService;
import cn.drenal.capcap.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 前台评论控制器
 */
@RestController
@RequestMapping("/forum/comment")
@RequiredArgsConstructor
public class ForumCommentController {

    private final CommentService commentService;
    private final UserService userService;
    
    @Autowired
    private CommentLikeMapper commentLikeMapper;

    /**
     * 获取作品评论列表
     *
     * @param artworkId 作品ID
     * @param current 当前页
     * @param size 每页大小
     * @return 评论分页列表
     */
    @SaIgnore
    @GetMapping("/artwork/{artworkId}/comments")
    public Response<Page<CommentVO>> getArtworkComments(
            @PathVariable Long artworkId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Comment> page = new Page<>(current, size);
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getArtworkId, artworkId);
        wrapper.eq(Comment::getStatus, 1); // 只查询已审核的评论
        wrapper.isNull(Comment::getParentId); // 只查询一级评论
        wrapper.orderByDesc(Comment::getCreateTime);
        Page<Comment> commentPage = commentService.page(page, wrapper);
        
        // 转换为VO，添加用户信息
        Page<CommentVO> commentVOPage = new Page<>(current, size, commentPage.getTotal());
        List<CommentVO> commentVOList = commentPage.getRecords().stream().map(comment -> {
            CommentVO vo = new CommentVO();
            BeanUtils.copyProperties(comment, vo);
            
            // 设置用户信息
            User user = userService.getById(comment.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
                vo.setUserAvatar(user.getAvatar());
            }
            
            // 获取回复列表
            if (comment.getId() != null) {
                LambdaQueryWrapper<Comment> replyWrapper = new LambdaQueryWrapper<>();
                replyWrapper.eq(Comment::getParentId, comment.getId());
                replyWrapper.eq(Comment::getStatus, 1); // 只查询已审核的评论
                replyWrapper.orderByAsc(Comment::getCreateTime);
                List<Comment> replies = commentService.list(replyWrapper);
                
                // 转换回复为VO
                List<CommentVO> replyVOList = replies.stream().map(reply -> {
                    CommentVO replyVO = new CommentVO();
                    BeanUtils.copyProperties(reply, replyVO);
                    
                    // 设置回复用户信息
                    User replyUser = userService.getById(reply.getUserId());
                    if (replyUser != null) {
                        replyVO.setUsername(replyUser.getUsername());
                        replyVO.setUserAvatar(replyUser.getAvatar());
                    }
                    
                    // 设置被回复用户信息
                    if (reply.getReplyUserId() != null) {
                        User replyToUser = userService.getById(reply.getReplyUserId());
                        if (replyToUser != null) {
                            replyVO.setReplyUsername(replyToUser.getUsername());
                        }
                    }
                    
                    return replyVO;
                }).collect(Collectors.toList());
                
                vo.setReplies(replyVOList);
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        commentVOPage.setRecords(commentVOList);
        return Response.success(commentVOPage);
    }

    /**
     * 添加作品评论
     *
     * @param artworkId 作品ID
     * @param comment 评论信息
     * @return 操作结果
     */
    @PostMapping("/artwork/{artworkId}/comment")
    public Response<Comment> addComment(@PathVariable Long artworkId, @RequestBody Comment comment) {
        // 设置当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        comment.setUserId(userId);
        comment.setArtworkId(artworkId);
        comment.setStatus(1); // 设置为已审核状态，简化流程
        comment.setLikeCount(0); // 初始点赞数为0
        
        Comment savedComment = commentService.createComment(comment);
        return Response.success(savedComment);
    }

    /**
     * 回复评论
     *
     * @param commentId 评论ID
     * @param comment 回复信息
     * @return 操作结果
     */
    @PostMapping("/reply/{commentId}")
    public Response<Comment> replyComment(@PathVariable Long commentId, @RequestBody Comment comment) {
        // 设置当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        comment.setUserId(userId);
        comment.setParentId(commentId);
        comment.setStatus(1); // 设置为已审核状态，简化流程
        comment.setLikeCount(0); // 初始点赞数为0
        
        // 获取原评论的作品ID
        Comment parentComment = commentService.getById(commentId);
        if (parentComment != null) {
            comment.setArtworkId(parentComment.getArtworkId());
        }
        
        Comment savedComment = commentService.createComment(comment);
        return Response.success(savedComment);
    }
    
    /**
     * 点赞/取消点赞评论
     *
     * @param commentId 评论ID
     * @return 操作结果
     */
    @PostMapping("/like/{commentId}")
    public Response<Boolean> likeComment(@PathVariable Long commentId) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 检查评论是否存在
        Comment comment = commentService.getById(commentId);
        if (comment == null) {
            return Response.error("评论不存在");
        }
        
        // 检查是否已点赞
        LambdaQueryWrapper<CommentLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommentLike::getUserId, userId)
                .eq(CommentLike::getCommentId, commentId);
        CommentLike existingLike = commentLikeMapper.selectOne(queryWrapper);
        
        boolean isLiked;
        if (existingLike == null) {
            // 未点赞，添加点赞
            CommentLike commentLike = new CommentLike();
            commentLike.setUserId(userId);
            commentLike.setCommentId(commentId);
            commentLikeMapper.insert(commentLike);
            
            // 更新评论点赞数
            comment.setLikeCount(comment.getLikeCount() + 1);
            commentService.updateById(comment);
            isLiked = true;
        } else {
            // 已点赞，取消点赞
            commentLikeMapper.delete(queryWrapper);
            
            // 更新评论点赞数
            if (comment.getLikeCount() > 0) {
                comment.setLikeCount(comment.getLikeCount() - 1);
                commentService.updateById(comment);
            }
            isLiked = false;
        }
        
        return Response.success(isLiked);
    }
    
    /**
     * 检查是否已点赞评论
     *
     * @param commentId 评论ID
     * @return 是否已点赞
     */
    @GetMapping("/is-liked/{commentId}")
    public Response<Boolean> isLikedComment(@PathVariable Long commentId) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 检查是否已点赞
        LambdaQueryWrapper<CommentLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommentLike::getUserId, userId)
                .eq(CommentLike::getCommentId, commentId);
        CommentLike existingLike = commentLikeMapper.selectOne(queryWrapper);
        
        return Response.success(existingLike != null);
    }
    
    /**
     * 删除评论
     *
     * @param commentId 评论ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{commentId}")
    public Response<Boolean> deleteComment(@PathVariable Long commentId) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 检查评论是否存在
        Comment comment = commentService.getById(commentId);
        if (comment == null) {
            return Response.error("评论不存在");
        }
        
        // 检查是否是评论作者
        if (!comment.getUserId().equals(userId)) {
            return Response.error("只能删除自己的评论");
        }
        
        // 删除评论
        boolean success = commentService.removeById(commentId);
        
        // 如果是一级评论，同时删除其下的所有回复
        if (success && comment.getParentId() == null) {
            LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Comment::getParentId, commentId);
            commentService.remove(wrapper);
        }
        
        return Response.success(success);
    }
}
